package com.bang.concurrency.example.singleton;

import com.bang.concurrency.annotations.NotRecommend;
import com.bang.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther: Bang
 * @Date: 2019/9/30 21:16
 * @Description: 单例模式 恶汉模式 借助static关键字完成类初始化话
 *  类变量,静态代码块的执行顺序是从上向下的
 *  在类加载过程中的初始化话过程中执行类构造器方法<clinit>
 *
 */
@ThreadSafe
@Slf4j
@NotRecommend
public class SingletonExample5 {

    // 私有化构造方法
    private SingletonExample5() {
    }

    private static volatile SingletonExample5 instance = new SingletonExample5();


    // 静态的工厂方法
    public static SingletonExample5 getInstance() {
        return instance;
    }

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        Set<SingletonExample5> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 500; i++) {
            service.execute(() -> {
                SingletonExample5 instance = SingletonExample5.getInstance();
                set.add(instance);
            });
        }
        service.shutdown();
        System.err.println(set.size());
    }


}
